<template>
    <div class="upload_box">
        <el-upload class="upload" :action="ocsAction" :before-upload="beforeUpload" :http-request="handleUpload"
            v-loading="loading" :show-file-list="false" :accept="myAccept">
            <el-button size="mini" type="primary">{{ btnTxt }}</el-button>
        </el-upload>
    </div>
</template>
<script>
import TcVod from 'vod-js-sdk-v6';
import { cosUpload, upload, fetchToken } from '@/api/kanke/textbook/material';
import { ACCEPT_ALL, ACCEPT_IMG, ACCEPT_VIDEO, ACCEPT_AUDIO, ACCEPT_DOC } from '@/config/upload';
export default {
    name: "KanKeTextbookMaterialUpload",
    props: {
        accept: {
            type: String,
            default: ''
        },
        type: {
            type: String,
            default: 'all'
        },
        onFinish: {
            type: Function,
        },
        btnTxt: {
            type: String,
            default: '上传素材'
        }
    },
    data() {
        return {
            loading: false,
            ocsAction: '/apikanke/material/ossUpload',
            typeMap: {
                'all': '',
                'doc': 1,
                'video': 2,
                'audio': 3,
                'image': 4
            },
            acceptMap: {
                'all': ACCEPT_ALL,
                'doc': ACCEPT_DOC,
                'video': ACCEPT_VIDEO,
                'audio': ACCEPT_AUDIO,
                'image': ACCEPT_IMG
            },
            fileSizeLimit: {
                'doc': 200 * 1024 * 1024,
                'video': 5 * 1024 * 1024 * 1024,
                'audio': 200 * 1024 * 1024,
                'image': 10 * 1024 * 1024
            },
            fileType: '',
            uploader: null
        };
    },
    computed: {
        myAccept() {
            return this.accept || this.acceptMap[this.type];
        }
    }
    ,
    methods: {
        handleUpload(e) {
            const file = e.file;
            if (['video', 'audio'].includes(this.fileType)) {
                // 使用 tc-vod 上传
                this.tcUpload(e);

            } else {
                // 使用 ocs 上传
                const formData = new FormData();
                formData.append('file', file);
                this.loading = true;
                cosUpload(formData).then((res) => {
                    this.loading = false;
                    if (res.code !== 200) {
                        this.$message.error(res.msg);
                        return
                    }
                    this.$emit('onFinish');
                })
            }
        },
        async getYDBSignature() {
            const res = await fetchToken();
            if (res.code !== 200) {
                return null;
            }
            return res.data.signature;
        },
        beforeUpload(file) {
            if (!file) return;
            // 检查文件名称长度
            if (file.name.length > 100) {
                this.$message.error('文件名不能超过100个字符');
                return false;
            }
            let fileType = '';
            const fileExt = file.name.split('.').pop().toLowerCase();
            // 如果是 all 类型 则判断当前的文件的类型
            if (this.type == 'all') {
                // 我想判断 文件类型 是哪一种
                // 1=>文档,2=>视频;3=>音频;4=>图片
                if (ACCEPT_AUDIO.includes(fileExt)) {
                    fileType = 'audio';
                } else if (ACCEPT_DOC.includes(fileExt)) {
                    fileType = 'doc';
                } else if (ACCEPT_IMG.includes(fileExt)) {
                    fileType = 'image';
                } else if (ACCEPT_VIDEO.includes(fileExt)) {
                    fileType = 'video';
                } else {
                    this.$message.error(`上传文件只支持${this.myAccept}格式!`);
                    return false;
                }
            }

            if (this.acceptMap[this.type].indexOf(fileExt) < 0) {
                this.$message.error(`上传文件只支持${this.myAccept}格式!`);
                return false;
            }

            // 限制文件大小
            if (this.fileSizeLimit[fileType] && file.size > this.fileSizeLimit[fileType]) {
                this.$message.error(`上传文件大小不能超过${this.fileSizeLimit[fileType] / 1024 / 1024}MB!`);
                return false;
            }
            this.fileType = fileType || this.type;
            return true

        },
        tcUpload(e) {
            const file = e.file;
            const tcVod = new TcVod({
                getSignature: this.getYDBSignature
            })
            if (this.uploader) {
                // 取消
                this.uploader.cancel();
            }
            this.loading = true;
            const uploader = tcVod.upload({
                mediaFile: file,
            })

            // 上传开始
            uploader.done().then((doneResult) => {
                this.loading = false;
                upload({
                    file_id: doneResult.fileId,
                    title: file.name,
                    type: this.typeMap[this.fileType],
                    file_mime: file.type
                }).then((result) => {
                    if (result.code == 200) {
                        this.$emit('onFinish');
                        this.$message.success('保存成功')

                    } else {
                        this.$message.error('保存失败')
                    }
                })

            }).catch((err) => {
                this.loading = false;
                this.$message.error('上传云点播失败')
            })
            this.uploader = uploader
        },
    }
}
</script>
<style lang="scss" scoped>
.upload_box {
    display: inline-block;
    margin-right: 20px;
}
</style>